'use strict'

const Controller = require('egg').Controller

const client_id =
  '14ed43a44a6d4627d1ab8f4c2636a50b6457a9f235124b79150449a3e1a66acd'
const client_secret =
  '51dfb762bbf7e139ac3198dbd23e9282f94bebdced01e26b1dc60a6bc38b7a20'
const axios = require('axios')
const redirect_uri = 'http://localhost:7001/api/oauth/redirect'
/**
 * 语雀 -> 支付宝 -> 语雀
 *
 * 自己的前端 -> 码云 code(用户信息) -> 自己的前端
 */

class UploadController extends Controller {
  async auth() {
    const { ctx, app } = this
    const { code } = ctx.query
    const response = await axios.post(
      `https://gitee.com/oauth/token?grant_type=authorization_code&code=${code}&client_id=${client_id}&redirect_uri=${redirect_uri}&client_secret=${client_secret}`
    )
    // 2. 拿token
    const access_token = response.data.access_token
    // 3. 拿码云部分用户信息
    const userInfo = await axios.get(
      `https://gitee.com/api/v5/user?access_token=${access_token}`
    )

    // 4. 跳转到前端页面
    console.log(userInfo.data.avatar_url)
    ctx.response.redirect(
      `http://localhost:8080/layout/home?access_token=${access_token}&avatar=${userInfo.data.avatar_url}&name=${userInfo.data.name}`
    )
  }
}

module.exports = UploadController
